// ==UserScript==
// @name           vkontakte.checker
// @namespace      http://misbug.blogspot.com
// @include        http://vkontakte.ru/*
// ==/UserScript==

var global = typeof unsafeWindow == 'undefined' ? window : unsafeWindow;

var Event = {
	
	AddEvent: function(object, type, handler)
	{
		if (object.addEventListener)
		{
			object.addEventListener(type, handler, true);
		}
		else if (object.attachEvent)
		{
			object.attachEvent('on' + type, handler);
		};
	},
	
	StopEvent: function(event)
	{
		event.stopPropagation && event.stopPropagation();
		event.preventDefault && event.preventDefault();
		event.cancelBubble = true;
		event.cancel = true;
		event.returnValue = false;
	}
	
};

var GetParams = function()
{
	var params = {};
	location.search.replace(/^\?(.*)$/, function($0, $1)
			{
				var p = $1.split('&');
				for (var i = 0; i < p.length; i++)
				{
					p[i].replace(/^([a-z0-9]+)(?:=(.*)?)?$/i, function($0, key, value)
						{
							params[key] = value;
						}
					)
				}
			}
		)
	return(params);
};

(function()
{
	var defaultTitle = document.title;
	
	if (location.host == 'vkontakte.ru')
	{
		var page = {
				params: GetParams()
			};
				
		if (/^\/id\d+$/.test(location.pathname) || /^\/profile\.php$/.test(location.pathname))
		{
			page.name = 'profile';
		}
		else if (/^\/mail\.php$/.test(location.pathname))
		{
			page.name = 'mail';
		}
		
		Event.AddEvent(window, 'keyup', function(event)
			{
				if ((event.keyCode == 1025 || event.keyCode == 192) && !event.shiftKey && !event.ctrlKey && !event.altKey)
				{
					if (!global.shown('br'))
					{
						document.getElementById('reply_field').value = '';
						global.quickReply('quickReply', 0, 0, 1);
						global.shide('br');
					}
				}
			}
		);
		
		var CheckFeed = function()
		{
			var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');

			document.title += ' ...';
			xhr.open('GET', 'http://vkontakte.ru/feed2.php', true);
			
			xhr.onreadystatechange = function()
			{
				if (xhr.readyState == 4)
				{
					if (xhr.status == 200)
					{
						var responseJSON = eval('(' + xhr.responseText + ')');
						var outputItems = [];
						
						for (var key in responseJSON)
						{
							if (typeof(responseJSON[key].count) == 'number' && responseJSON[key].count > 0)
							{
								outputItems.push(key + ': ' + responseJSON[key].count);
							}
						}
						
						if (outputItems.length > 0)
						{
							document.title = outputItems.join(', ');
						}
						else
						{
							document.title = defaultTitle;
						}
						
					}
					else
					{
						document.title += ' ' + xhr.status;
					}
				}
			}
			
			xhr.send(null);
		}
		
		var ReloadWall = function()
		{
			if (page.name == 'profile')
			{
				var wall = document.getElementById('wall');
				if (wall !== null && document.getElementsByClassName && typeof global.makeFRequest != 'undefined')
				{
					var header = document.getElementsByClassName('header', wall)[0];
					if ((typeof header == 'object' && document.getElementsByClassName('upArrow', header).length === 0) || true)
					{
						global.makeFRequest('wall.php?act=get10&wpage=0&g=0', 2);
					}
				}
			}
		}
		
		var GetHistory = function()
		{
			var toId = document.getElementById('to_id');
			var mid = toId !== null ? toId.value : page.params.to;
			
			if (page.name == 'mail' && typeof mid == 'string')
			{
				var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');
				
				xhr.open('POST', 'mail.php?act=history');
				
				xhr.onreadystatechange = function()
				{
					if (xhr.readyState == 4)
					{
						if (xhr.status == 200)
						{
							document.getElementById('historyContents').innerHTML = xhr.responseText;
						}
					}
				}
				
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=windows-1251');
			
				xhr.send('mid=' + mid);
			}
		}
		
		var kotUrlEncode = function(s)
		{
			return s.replace("%", "%25", "g").replace("&", "%26", "g").replace("+", "%2B", "g").replace("?", "%3F", "g");
		}
		
		var PostMessage = function()
		{
			var postMessage = document.getElementById('postMessage');
			var p = [];
			
			var fields = postMessage.getElementsByTagName('input');
			
			for (var i = 0; i < fields.length; i++)
			{
				p.push(fields[i].name + '=' + fields[i].value);
			}
			
			var messageField = document.getElementById('reply_field');
			
			p.push(messageField.name + '=' + kotUrlEncode(messageField.value));
			
			postMessage.disabled = true;
			messageField.disabled = true;
			
			var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');

			xhr.open('POST', 'http://vkontakte.ru/mail.php', true);
			
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			
			xhr.onreadystatechange = function()
			{
				if (xhr.readyState == 4)
				{
					if (xhr.status == 200)
					{
						messageField.value = '';
						GetHistory();
					}
					postMessage.disabled = false;
					messageField.disabled = false;
					messageField.focus();
				}
			}
			
			xhr.send(p.join('&'));
			return(false);
		}
		
		var ReloadMessenger = function()
		{
			if (page.name == 'mail' && (page.params.act == 'show' || page.params.act == 'write') && (page.params.to || page.params.id))
			{
				var postMessage = document.getElementById('postMessage');
				
				if (postMessage !== null)
				{
					if (postMessage.target == '')
					{
						var oldMessageField = document.getElementById('reply_field') || document.getElementsByName('message')[0];
						
						if (oldMessageField)
						{
							var messageField = oldMessageField.parentNode.insertBefore(document.createElement('textarea'), oldMessageField);
							
							oldMessageField.parentNode.removeChild(oldMessageField);
							
							messageField.id = 'reply_field';
							messageField.name = 'message';
							
							if (page.params.act == 'write')
							{
								messageField.style.width = '250px';
							}
							else
							{
								messageField.style.margin = '5px 12px';
								messageField.style.width = '400px';
							}
							
							messageField.style.height = '100px';
							
							messageField.focus();
							
							
							Event.AddEvent(messageField, 'keypress', function(event)
								{
									if (event.keyCode == 10 || (event.ctrlKey && event.keyCode == 13))
									{
										PostMessage();
									} 
								}
							);
							
							postMessage.target = '_self';

						}
						
						document.getElementById('progr').style.visibility = 'visible';
						document.getElementById('progr').style.display = 'inline';
					}
					
					GetHistory();
				}
			}
		}
		
		var Daemon = function()
		{
			CheckFeed();

			ReloadWall();
			
			ReloadMessenger();
			
			setTimeout(Daemon, 10000);
		}
		
		Daemon();
	}

}
)();